package com.cms.service.impl;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.cms.entity.SmsVerifyCode;
import com.cms.service.SmsVerifyCodeService;
import com.cms.support.Result;
import com.cms.support.SMSUtils;

@Service
public class SmsVerifyCodeServiceImpl extends BaseServiceImpl implements
		SmsVerifyCodeService {
	public static final Logger LOGGER = Logger
			.getLogger(SmsVerifyCodeServiceImpl.class);
	SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");

	@Override
	public Result sendSms(String phone,String id) {
		if (StringUtils.isBlank(phone)) {
			return new Result(false, "请求参数不正确");
		}

		SmsVerifyCode entity = new SmsVerifyCode();
		entity.setId(id);
		entity.setCreateDate(new Date());
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new Date());
		calendar.add(Calendar.HOUR, 2);
		entity.setExpierDate(calendar.getTime());
		entity.setPhoneNum(phone);
		entity.setVerifyCode(this.randSix());
		entity.setVerifyCount(3);
		try {
			baseDao.saveOrUpdate(entity);
		} catch (Exception e) {
			return new Result(false, "系统错误[数据库操作错误 ]");
		}
		try {
			return SMSUtils.sendSMS(entity.getPhoneNum(),
					"验证码" + entity.getVerifyCode() + ",请勿泄漏");
		} catch (Exception e) {
			e.printStackTrace();
			return new Result(false, "系统异常:"+e.getMessage());
		}
	}

	@Override
	public Result verifySms(String codeId,String phone,String code) {
		SmsVerifyCode old = baseDao.get(SmsVerifyCode.class, codeId);
		if (old != null) {
			old.setVerifyCount(old.getVerifyCount() - 1);
			baseDao.save(old);
		} else {
			return new Result(false, "短信验证码无效");
		}
		if (old.getExpierDate() != null
				&& old.getExpierDate().before(new Date())) {
			return new Result(false, "验证码已超时,请重新发送");
		}
		if (old.getVerifyCount() < 0) {
			return new Result(false, "验证码次数已超过上限");
		}
		if (old.getPhoneNum() != null
				&& !old.getPhoneNum().equals(phone)) {
			return new Result(false, "验证电话号码不一致");
		} else if (!old.getVerifyCode().equals(code)) {
			return new Result(false, "验证码错误");
		}
		return new Result(true, "验证通过");
	}

	@Override
	public void deleteSms() {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(new Date());
		calendar.add(Calendar.HOUR, -24);
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		baseDao.sqlUpdate(
				"delete from T_PSS_SMSVERIFYCODE where createDate < ?",
				sf.format(calendar.getTime()));
	}

	/**
	 * 生成六位数验证码
	 * 
	 * @return
	 */
	private String randSix() {
		String pin = "";
		while (pin.length() < 6) {
			pin += (int) (Math.random() * 10);
		}
		return pin;
	}

}
